//
// Created by de on 3/24/21.
//

#ifndef FORCEEIGENTEST_TSTATECONTROLLER_H
#define FORCEEIGENTEST_TSTATECONTROLLER_H

#include <State/monitor/MonitorInterface.h>
#include <SqlController/dao/SqlDaoInterface.h>
#include "State/Factory/StateFactory.h"
#include "boost/weak_ptr.hpp"
#include "Global/GlobalVar.h"
#include "atomic"
#include "ros/ros.h"
namespace HsState{


enum TStateDevice{
    Ready,
    Stop,
    Falel,
    Running,
};


class TStateController {
public:
    explicit  TStateController(ros::NodeHandle * ptr);

    ~TStateController();

    //block
    /*
     *
     */
    void initDevice();

    //non - block
    void stopDevice();

    //
    void EmpStopDevice();

    StateStatus getDeviceStatus();

    void runningThreading();

    // work thread  function
    void runLoop();
    void monitorDeviceThread(); // only extern threading
    void monitorDevice(DeviceState2Commu &deviceState2Commu);
    void AutoResetDevice();
    void RunSignalAction();
    //block
    WorkResult getWorkResult();

    void getDataBaseLog();

    void selectAllItem(std::vector<WorkResult>& v_workresult);

    //
    bool initDataBase();

    //
    void resetDevice();

    void resetDataRecord();


    void resetSystemAndClearWarm();

    void setThreadLoopCount(int count);

private:
    void setCurrentState( std::shared_ptr<PlaformStateAbstract>  &p_RunningState);
    void initParam();
    std::string getStateInfo(StateStatus state);
    void initHandler(ros::NodeHandle *p_node);
private:
    std::shared_ptr<PlaformStateAbstract> p_InitState;
    std::shared_ptr<PlaformStateAbstract> p_PrepareState;
    std::shared_ptr<PlaformStateAbstract> p_ErrorState;
    std::shared_ptr<PlaformStateAbstract> p_StopState;
    std::shared_ptr<PlaformStateAbstract> p_RunningState;
    //p_SqlDaoInterface
    std::shared_ptr<SqlDaoInterface> p_SqlDaoInterface;
    std::shared_ptr<PlaformStateAbstract> p_CurrentState;

    std::shared_ptr<CSemaphore>  p_EGloalSemaphore,p_RunGloalSemaphore,p_ResultGloalSemaphore;

    std::shared_ptr<MonitorInterface> p_MonitorInterface;

    StateSelection* p_stateSelection;

    std::atomic_bool b_StopEnable, b_CathError;
    std::atomic_int ResetCount, m_ThreadCount;
    E_State estate;

    ros::NodeHandle* p_node;
    std::atomic_bool b_ReSumeAction;

    bool first_enter = false;;

    double clock_time=0.0;

};

}
#endif //FORCEEIGENTEST_TSTATECONTROLLER_H
